package com.chenshuang.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class JDBCTools {
    static DataSource dataSource;
    private static ThreadLocal<Connection> t = new ThreadLocal<>();
    static {
        try {
            Properties properties = new Properties();
            InputStream asStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties");
            properties.load(asStream);

            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try {
            Connection connection = t.get();
            if (connection==null){
                t.set(dataSource.getConnection());
                connection =  t.get();
            }
            return connection;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static void release(){
        Connection connection = t.get();
        t.remove();
        if (connection!=connection){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
